package com.nari.ncps.screen.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.nari.ncps.screen.common.pojo.ApiResponse;
import com.nari.ncps.screen.dto.excelbase.ExcelBasicInfo;
import com.nari.ncps.screen.dto.excelbase.ExcelEntityRegistry;
import com.nari.ncps.screen.service.excelhandler.ExcelDataHandler;
import com.nari.ncps.screen.service.excelhandler.ExcelParseService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ExcelParseServiceImpl implements ExcelParseService {

    //存放所有实现类的集合
    private final Map<Class<?>, ExcelDataHandler<?>> handlerMap;

    // Spring 会自动注入所有 ExcelDataHandler 的实现
    public ExcelParseServiceImpl(List<ExcelDataHandler<?>> handlers) {
        this.handlerMap = handlers.stream()
                .collect(Collectors.toMap(
                        handler -> (Class<?>) GenericTypeResolver.resolveTypeArgument(handler.getClass(), ExcelDataHandler.class),
                        Function.identity()
                ));
    }


    @Override
    public ApiResponse<Object> excelParseToDB(XSSFWorkbook wb, ExcelBasicInfo excelBasicInfo, byte[] byteArray) {

        try (InputStream inputStream1 = new ByteArrayInputStream(byteArray)) {
            ImportParams params = new ImportParams();
            // 设置标题行数（跳过这些行）
            params.setTitleRows(excelBasicInfo.getTableDataStartRow());
            // 设置表头行数（通常为1行）
            params.setHeadRows(1);
            // 开始读取的数据行（从第0行开始）
            params.setStartRows(0);
            // 要读取的数据行数
            params.setReadRows(excelBasicInfo.getDataEnd()-excelBasicInfo.getDataBegin());

            System.out.println(excelBasicInfo.getDataEnd()+","+excelBasicInfo.getDataBegin());

            Class<?> entityClass = ExcelEntityRegistry.getEntityClassByTableName(excelBasicInfo.getTableEnName());

            List<?> dataList = ExcelImportUtil.importExcel(inputStream1, entityClass, params);

            // 类型安全地调用对应处理器
            ExcelDataHandler<?> handler = handlerMap.get(entityClass);
            if (handler == null) {
                throw new IllegalArgumentException("未找到处理器: " + entityClass);
            }

            // 安全转型并调用
            handler.handle((List) dataList);

//            // 如果需要强类型，可以用反射或后续转换
//            if (entityClass == CoalOpermonEquipFaultDto.class) {
//                List<CoalOpermonEquipFaultDto> typedList = (List<CoalOpermonEquipFaultDto>) dataList;
//                // 处理业务逻辑
//                //输出
//                for(CoalOpermonEquipFaultDto dto : typedList){
//                    System.out.println(dto.getMonth());
//                }
//                //入库
//            }

            //清空缓存
            dataList.clear();

        } catch (Exception e) {
            return ApiResponse.failed("解析出错");
        }

 /*

            if(excelBasicInfo.getTableEnName().equalsIgnoreCase("coal_prodoper_output")) {

                try (InputStream inputStream1 = new ByteArrayInputStream(byteArray)) {
                        // 在这里使用 inputStream1
                        // 例如：读取数据、处理流等
                    ImportParams params1 = new ImportParams();
                    // 设置标题行数（跳过这些行）
    //            params1.setTitleRows(excelBasicInfo.getDataBegin());
    //            params1.setTitleRows(6);
                    params1.setTitleRows(excelBasicInfo.getTableDataStartRow());
                    // 设置表头行数（通常为1行）
                    params1.setHeadRows(1);
                    // 开始读取的数据行（从第0行开始）
                    params1.setStartRows(0);
                    // 要读取的数据行数
                    params1.setReadRows(excelBasicInfo.getDataEnd()-excelBasicInfo.getDataBegin());
    //            params1.setReadRows(11);

                    System.out.println(excelBasicInfo.getDataEnd()+","+excelBasicInfo.getDataBegin());

    //            List<?> targetInStandardExcelList = ExcelImportUtil.importExcel(inputStream1, T.class, params1);

                    List<CoalOpermonEquipFaultDto> targetInStandardExcelList = ExcelImportUtil.importExcel(inputStream1, CoalOpermonEquipFaultDto.class, params1);

                    //输出
                    for(CoalOpermonEquipFaultDto dto : targetInStandardExcelList){
                        System.out.println(dto.getMonth());
                    }
                    //入库

                    //清空缓存
                    targetInStandardExcelList.clear();


                } catch (Exception e) {
                    return ApiResponse.failed("解析出错");
                }

            } else if(excelBasicInfo.getTableEnName().equalsIgnoreCase("coal_safetyenv_alarm")) {

                try (InputStream inputStream2 = new ByteArrayInputStream(byteArray)) {

//                    Sheet sheet = wb.getSheetAt(0);
//                    int lastRowNum = sheet.getLastRowNum();
//
//                    System.out.println("Sheet总行数: " + lastRowNum);
//                    System.out.println("尝试读取的行范围: 126-129");
//
//                    if (lastRowNum < 129) {
//                        System.out.println("错误: 行数不足，最大行号: " + lastRowNum);
//                    }

                    ImportParams params1 = new ImportParams();
                    // 关键配置
                    params1.setTitleRows(125);     // 前125行都是标题（跳过）
                    params1.setHeadRows(1);        // 第126行是表头行
                    params1.setStartRows(0);     // 数据从第127行开始（索引从0开始）
                    params1.setReadRows(3);        // 读取3行数据（127,128,129行）

                    List<CoalSafetyenvAlarmDto> excelList = ExcelImportUtil.importExcel(inputStream2,
                            CoalSafetyenvAlarmDto.class, params1);

                    //输出
                    for(CoalSafetyenvAlarmDto dto : excelList){
                        System.out.println(dto.getMonth());
                    }

                    //入库

                    //清空缓存
                    excelList.clear();

                } catch (Exception e) {
                    System.err.println("Excel解析错误: " + e.getMessage());
                    return ApiResponse.failed("解析出错");
                }
            }

*/
        return ApiResponse.succeed("导入成功");
    }


}
